package cn.mulanbay.message.web.controller;

import cn.mulanbay.business.bean.SysMessageBean;
import cn.mulanbay.business.bean.UserMessageBean;
import cn.mulanbay.common.bean.ResultBean;
import cn.mulanbay.common.exception.ErrorCode;
import cn.mulanbay.common.util.BeanCopy;
import cn.mulanbay.message.handler.MessageNotifyHandler;
import cn.mulanbay.message.persistent.service.UserMessageService;
import cn.mulanbay.message.web.bean.request.message.MessageSearch;
import cn.mulanbay.persistent.entity.ErrorCodeDefine;
import cn.mulanbay.persistent.entity.UserMessage;
import cn.mulanbay.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 消息
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@RestController
@RequestMapping("userMessage")
public class UserMessageController extends BaseController {

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    MessageNotifyHandler messageNotifyHandler;

    /**
     * 获取列表数据
     *
     * @return
     */
    @RequestMapping(value = "/getData", method = RequestMethod.GET)
    public ResultBean getData(MessageSearch sf) {
        return callbackDataGrid(userMessageService.getDataList(sf));
    }

    /**
     * 添加用户消息
     *
     * @return
     */
    @RequestMapping(value = "/addUserMsg", method = RequestMethod.POST)
    public ResultBean addUserMsg(@RequestBody @Valid UserMessageBean umb) {
        UserMessage um = new UserMessage();
        BeanCopy.copyProperties(umb, um);
        ErrorCodeDefine ecd = this.getErrorCodeDefine(umb.getCode());
        um.setLogLevel(ecd.getLevel());
        um.setBussType(ecd.getBussType());
        messageNotifyHandler.addNotifyMessage(um);
        return callback(null);
    }

    /**
     * 添加系统消息
     *
     * @return
     */
    @RequestMapping(value = "/addSysMsg", method = RequestMethod.POST)
    public ResultBean addSysMsg(@RequestBody @Valid SysMessageBean smb) {
        messageNotifyHandler.addMessageToNotifier(smb);
        return callback(null);
    }

    /**
     * 获取错误代码定义
     * @param code
     * @return
     */
    private ErrorCodeDefine getErrorCodeDefine(Integer code){
        ErrorCodeDefine ecd = userMessageService.getErrorCodeDefine(code);
        if (ecd == null) {
            ecd = userMessageService.getErrorCodeDefine(ErrorCode.COMMON_CODE);
        }
        return ecd;
    }
}
